package v1

import (
	"yuanxin-admin/internal/repository"

	"gitee.com/botaoshow/yuanxin/web/response"
	"gitee.com/botaoshow/yuanxin/web/utils/pages"
	"github.com/gin-gonic/gin"
)

type SysLogController struct {
}

func NewSysLogController() *SysLogController {
	return &SysLogController{}
}

func (s *SysLogController) Login(c *gin.Context) {
	username := c.DefaultQuery("username", "")
	ip := c.DefaultQuery("ip", "")
	status := c.DefaultQuery("status", "")
	var pg pages.PageDTO
	err := c.ShouldBind(&pg)
	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	offset, limit := pages.GetOffsetAndLimitByPageDTO(&pg)

	q := repository.SysLoginLog.WithContext(c)

	if username != "" {
		q = q.Where(repository.SysLoginLog.Username.Like(username))
	}
	if ip != "" {
		q = q.Where(repository.SysLoginLog.IP.Like(ip))
	}
	if status != "" {
		q = q.Where(repository.SysLoginLog.Status.Eq(status))
	}
	result, count, err := q.Order(repository.SysLoginLog.LoginTime.Desc()).FindByPage(offset, limit)
	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	page := pages.NewPage(result, count, pg.PageNum, pg.PageSize)
	response.Success(c, page)
}

func (s *SysLogController) Oper(c *gin.Context) {
	operName := c.DefaultQuery("operName", "")
	operType := c.DefaultQuery("operType", "")
	status := c.DefaultQuery("status", "")
	var pg pages.PageDTO
	err := c.ShouldBind(&pg)
	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	offset, limit := pages.GetOffsetAndLimitByPageDTO(&pg)
	q := repository.SysOperLog.WithContext(c)

	if operName != "" {
		q = q.Where(repository.SysOperLog.OperName.Like(operName))
	}
	if operType != "" {
		q = q.Where(repository.SysOperLog.OperType.Eq(operType))
	}
	if status != "" {
		q = q.Where(repository.SysOperLog.Status.Eq(status))
	}

	result, count, err := q.Order(repository.SysOperLog.OperTime.Desc()).FindByPage(offset, limit)

	if err != nil {
		response.Fail(c, err.Error())
		return
	}
	page := pages.NewPage(result, count, pg.PageNum, pg.PageSize)
	response.Success(c, page)
}
